<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>分割数组为连续子序列</title>
</head>

<body>
  <script>
    var isPossible = function (nums) {
      let max = nums[nums.length - 1]
      let arr = Array(max + 2).fill(0)
      let tail = Array(max + 2).fill(0)
      for (let n of nums) arr[n]++
      for (let n of nums) {
        if (!arr[n]) continue
        if (tail[n - 1] > 0) { // 后面的
          tail[n - 1]--
          tail[n]++
        } else if (arr[n + 1] > 0 && arr[n + 2] > 0) { // 头部
          arr[n + 1]--
          arr[n + 2]--
          tail[n + 2]++
        } else {
          return false
        }
        arr[n]--
      }
      return true
    };
    console.log(isPossible([1, 2, 3, 4, 4, 5]));
  </script>
</body>

</html>